package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.BaseContext;
import com.itheima.common.CustomExpection;
import com.itheima.dto.OrdersDto;
import com.itheima.mapper.OrdersMapper;
import com.itheima.pojo.*;
import com.itheima.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;
    @Override
    public void submit(Orders orders) {
        Long userId = BaseContext.getCurrentId();
        // 1、查询购物车数据：select * from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(userId != null,ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(lqw);
        if(shoppingCarts == null && shoppingCarts.size() == 0){
              throw new CustomExpection("购物车为空,不能下单");
        }
        //2、查询用户数据 select * from user where id = ?
        User user = userService.getById(userId);
        // 3、根据地址id查询地址数据 select * from address_book where id = ?
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        long orderId = IdWorker.getId();//订单号
        //BigDecimal amount = new BigDecimal(0);//总价
        AtomicInteger amount = new AtomicInteger(0);
        //保存订单明细数据:点了哪些菜品或套餐
//        for (ShoppingCart shoppingCart : shoppingCarts) {
//            OrderDetail orderDetail = new OrderDetail();
//            BeanUtils.copyProperties(shoppingCart,orderDetail);
//            //orderId单独设置
//            orderDetail.setOrderId(orderId);
//            //金额单独设置
//            //orderDetail.setAmount(amount);
//            BigDecimal price = shoppingCart.getAmount();
//            System.out.println(price+"==============------------------");
//            BigDecimal number = new BigDecimal(shoppingCart.getNumber());
//            System.out.println(number+"================");
//            orderDetail.setAmount(price.multiply(number));//设置订单总价(数量*单价)
//            amount.add(orderDetail.getAmount());//总价添加到数据库
//            System.out.println(amount+"-----------------");
//            orderDetailService.save(orderDetail);
//        }
        //组装订单明细信息
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        //保存订单数据,有许多订单需要单独设置
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());//订单创建时间
        orders.setCheckoutTime(LocalDateTime.now());//订单结账时间
        orders.setStatus(2);//1.待付款  2.待派送  3.已派送  4.已完成  5.已取消
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName()) == null? "": addressBook.getProvinceName()
                            +addressBook.getCityName() == null? "":addressBook.getCityName()
                            +addressBook.getDistrictName() == null? "":addressBook.getDistrictName()
                            +addressBook.getDetail() == null? "":addressBook.getDetail());//省,市,区域加详细地址
        this.save(orders);//保存订单数据
        orderDetailService.saveBatch(orderDetails);
        //删除当前用户的订单数据
        // delete from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> lqw2 = new LambdaQueryWrapper<>();
        lqw2.eq(ShoppingCart::getUserId,userId);
        shoppingCartService.remove(lqw2);
    }
}
